package com.gzx.plugin.tjzy.modular.founds.lock;

import lombok.extern.java.Log;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Log
@Service
public class RedisTransLock {
    public static final String LOCK_KEY = "TRANS_TYPE_LOCK";
    private final RedissonClient redissonClient;

    // 确保RedissonClient被正确注入
    public RedisTransLock(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 获取锁，失败时重试三次
     */
    public boolean getLock() {
        RLock rLock = null;
        int retryCount = 0;
        boolean lockAcquired = false;

        while (retryCount < 3) {
            try {
                rLock = redissonClient.getLock(LOCK_KEY);
                // 使用tryLock 来防止死锁或锁获取失败 尝试获取锁，最多等待10秒，最多持有10秒
                if (rLock.tryLock(10, 10, TimeUnit.SECONDS)) {
                    lockAcquired = true;
                    break;
                } else {
                    retryCount++;
                    log.warning("无法获取到锁，重试次数: " + retryCount);
                }
            } catch (InterruptedException e) {
                // 处理异常，存表（id，租户id，消费方式，bo对象，删除标志） FIX
                log.warning("获取分布式锁异常");
                retryCount++;
                //线程被中断，抛出异常
                Thread.currentThread().interrupt();
            } finally {
                if (lockAcquired && rLock != null && rLock.isHeldByCurrentThread()) {
                    try {
                        rLock.unlock();
                    } catch (Exception e) {
                        log.warning("释放锁异常");
                    }
                }
            }
        }

        if (!lockAcquired) {
            log.warning("重试三次后仍无法获取到锁");
        }

        return lockAcquired;
    }
}